<template>
  <create-view
    :loading="loading"
    :body-style="{ height: '100%'}">
    <flexbox
      direction="column"
      align="stretch"
      class="crm-create-container"
      style="height: 100%">
      <flexbox class="crm-create-header">
        <div style="flex:1;font-size:17px;color:#333;">{{title}}</div>
        <img
          class="close"
          src="@/assets/img/task_close.png"
          @click="hidenView" >
      </flexbox>
      <flexbox style="height: calc(100% - 60px);overflow: auto" v-if="crmType == 'quotation'">
          <component
            :is="'CrmQuotationPreview'"
            :detail="detailData"
            :list="listData"
            :action="{type: 'export'}"/>
      </flexbox>
      <flexbox style="height: calc(100% - 60px);overflow: auto" v-if="crmType == 'contract'">
          <component
            :is="'CrmContractPreview'"
            :contractInfo="detailData"
            :action="{type: 'export'}"/>
      </flexbox>
      <flexbox justify="flex-end" align="center" style="margin-top: 2px">
          <!-- <el-button type="primary" @click="refresh">
              刷新
          </el-button> -->
          <el-button v-if="showExportButton" type="primary" @click="exportPreviewPdf">
              导出为PDF
          </el-button>
      </flexbox>
    </flexbox>
  </create-view>
</template>

<script>
import { mapGetters } from 'vuex'
import CreateView from '@/components/CreateView'
// 报价
import CrmQuotationPreview from '@/views/customermanagement/quotation/components/CrmQuotationPreview'
import { crmQuotationRead } from '@/api/customermanagement/quotation'
// 合同
import CrmContractPreview from '@/views/customermanagement/contract/components/CrmContractPreview'
import { crmContractRead } from '@/api/customermanagement/contract'

import { addExportRecord } from '@/api/customermanagement/common'
import crmTypeModel from '@/views/customermanagement/model/crmTypeModel'
import { pageToPdf } from "@/utils/exportHtmlToPdf.js"
export default {
    name: 'CRMPreview',
    props: {
        /** 模块ID */
        id: [String, Number],
        /** 没有值就是全部类型 有值就是当个类型 */
        crmType: {
            type: String,
            default: ''
        },
    },
    data(){
        return {
            loading: false,
            detailData: {},
            listData: [],
            multiple: 1, //页数
        }
    },
    computed: {
        ...mapGetters(['crm', 'CRMConfig']),
        title(){
            if(this.crmType === 'quotation'){
                return '预览报价单'
            }
            if(this.crmType === 'contract'){
                return '预览合同'
            }
        },
        showExportButton(){
            if(this.crmType === 'quotation'){
                return this.crm[this.crmType].exportQuotation && this.detailData.checkStatus === 1;
            }
            if(this.crmType === 'contract'){
                return this.crm[this.crmType].exportContract && this.detailData.entity && this.detailData.entity.checkStatus === 1;
            }
            
        }
    },
    components: {
        CreateView,
        CrmQuotationPreview,
        CrmContractPreview
    },
    mounted() {
        console.log(this.id)
        this.getDetial();
    },
    methods: {
        getDetial() {
            this.loading = true
            let param = {};
            param[this.crmType + 'Id'] = this.id;
            let request = this.getIndexRequest();
            request(param).then(res => {
                this.loading = false
                if(this.crmType === 'quotation'){
                    this.detailData = res.data.baseInfo;
                    this.listData = res.data.listData;
                }
                if(this.crmType === 'contract'){
                    this.detailData = res.data;
                }
                
            }).catch(() => {
                this.loading = false
            })
        },

         /** 获取列表请求 */
        getIndexRequest() {
            console.log(this.crmType)
            if (this.crmType === 'contract') {
                return crmContractRead  
            } else if (this.crmType === 'quotation') {
                return crmQuotationRead
            }
        },

        // 导出
        exportPreviewPdf(){
            let name = '文件';
            let target = '';
            if(this.crmType == 'quotation'){
                name = "报价单：" + this.detailData.quotationNumber;
                target = document.getElementById("quotationInfo")
            }
            if(this.crmType == 'contract'){
                name = "合同：" + this.detailData.entity.num;
                target = document.getElementById("contractInfo")
            }
            this.loading = true;
            var a4w = 170
            var a4h = 280 // A4大小，210mm x 297mm，四边各保留20mm的边距，显示区域170x257
            // var imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度
            var pageHeight = Math.floor(a4h * target.scrollWidth / a4w) - 20 // 按A4显示比例换算一页图像的像素高度
            console.log('dev:'+pageHeight)
            let multiple = 0
            // 一般内容
            let lableListID = document.getElementsByClassName('target-node-item')
            for (let i = 0; i < lableListID.length; i++) {
                
                multiple = Math.ceil((lableListID[i].offsetTop + lableListID[i].offsetHeight + 40) / pageHeight) // 页数
                
                let divParent = lableListID[i].parentNode // 获取该div的父节点
                if(divParent.className.indexOf('change-page') != -1){
                    let newNode = document.createElement('div')
                    newNode.className = 'node-tag';
                    newNode.style.background = '#ffffff'
                    let surplusHeight =  multiple * pageHeight - (divParent.offsetTop + divParent.offsetHeight)
                    newNode.style.height = surplusHeight > 0 ? surplusHeight + 'px' : '80px'
                    divParent.appendChild(newNode)
                }
                if (this.isSplit(lableListID, i, multiple, pageHeight)) {
                    // if(divParent.getAttribute("class") == 'change-page'){
                    //     console.log('换页')
                    // }
                    let _H =  multiple > 1 ? (multiple - 1) * pageHeight - (lableListID[i].offsetTop) : 0;
                    
                    let table = lableListID[i].getElementsByTagName('table');
                    if(table.length){
                        let nodes = [];
                        
                        let heads = table[0].getElementsByTagName('thead');
                        for(let i=0;i<heads.length;i++){
                            nodes.push(heads[i]);
                        }
                    
                        let trs = table[0].getElementsByTagName('tr');
                        for(let i=0;i<trs.length;i++){
                            nodes.push(trs[i]);
                        }

                        let allOffsetHeight = 0;
                        for(let i=0;i<nodes.length;i++){
                            allOffsetHeight += nodes[i].offsetHeight;
                            let divParent = nodes[i].parentNode // 获取该div的父节点
                            if(allOffsetHeight + 40 > _H ){
                                let newNode = document.createElement('div')
                                newNode.className = 'node-tag';
                                newNode.style.background = '#ffffff'
                                newNode.style.width = '100%'
                                newNode.style.height = nodes[i].offsetHeight + 40 + 'px'
                                divParent.insertBefore(newNode, nodes[i])
                                break;
                            }
                        }
                    }else{
                        let newNode = document.createElement('div')
                        newNode.className = 'node-tag';
                        newNode.style.background = '#ffffff'
                        newNode.style.width = '100%'
                        newNode.style.height = _H + 40 + 'px'
                        let next = lableListID[i].nextSibling // 获取div的下一个兄弟节点
                        divParent.insertBefore(newNode, lableListID[i])
                    }
                    
                }
                
            }
            // 页码
            for(let i=0;i<multiple;i++){
                // let pageLine = document.createElement('div')
                // pageLine.className = 'node-tag';
                // pageLine.style.position = "absolute";
                // pageLine.style.width = '100%';
                // pageLine.style.border = '1px solid #000';
                // pageLine.style.top = ((i+1) * pageHeight) + 'px';
                // target.appendChild(pageLine)

                let newNode = document.createElement('div')
                newNode.className = 'node-tag';
                newNode.style.position = "absolute";
                newNode.style.width = '100%';
                newNode.style.fontSize = '16px';
                newNode.style.top = ((i+1) * pageHeight - 16) + 'px';
                newNode.style.display = "flex";
                newNode.style.justifyContent="space-around";
                newNode.style.alignItems="center";
                // 左线
                let leftLine = document.createElement('span');
                leftLine.style.width ="40%";
                leftLine.style.height ="1px";
                leftLine.style.borderTop ="1px solid #7d7676";

                // 页码
                let content = document.createElement('span');
                content.innerHTML= (i+1) + " / " + multiple;
                
                //右线
                let rightLine = document.createElement('span');
                rightLine.style.width ="40%";
                rightLine.style.height ="1px";
                rightLine.style.borderTop ="1px solid #7d7676";
                
                newNode.appendChild(leftLine);
                newNode.appendChild(content);
                newNode.appendChild(rightLine);
                target.appendChild(newNode)
            }
            // this.loading = false;
            // return
            let result = pageToPdf(target,name,'morePage',null,null,this.multiple).then(res => {
                this.refresh();
                this.addExportRecord();
                this.loading = false;
                this.$message({
                    message: '导出成功',
                    type: 'success'
                });
            }).catch(res => {
                this.loading = false;
                this.$message.error('导出失败');
            });
            
        },

        //如果导出成功，则记录导出记录
        addExportRecord(){
            let param = {
                actionId: this.id,
                types: crmTypeModel[this.crmType]
            }
            addExportRecord(param).then(res => {})
        },
        
        // 恢复页面
        refresh(){
            let nodeTags = document.getElementsByClassName('node-tag');
            this.multiple = 1;
            for(let i=0;i<nodeTags.length;i++){
                //删除元素 元素.parentNode.removeChild(元素);
                if (nodeTags[i] != null) nodeTags[i].parentNode.removeChild(nodeTags[i]); 
                this.refresh();
            }
        },

        // 判断当前元素是否超过截取的页面高度
        isSplit (nodes, index, multiple , onePageHeight) {
            // if (nodes[index].offsetTop + nodes[index].offsetHeight < pageHeight && nodes[index + 1] && nodes[index + 1].offsetTop + nodes[index + 1].offsetHeight > pageHeight) {
            //     return true
            // }
            // if(index>=88){
            //     console.log(multiple)
            //     debugger
            // }
            if( multiple > this.multiple ){
                this.multiple = multiple;
                return true;
            }
            return false;
            let isTopHeight = nodes[index].offsetHeight > ((multiple - 1) * onePageHeight - nodes[index].offsetTop);
            let isPageHeight = nodes[index].offsetTop + nodes[index].offsetHeight + 20> (multiple - 1) * onePageHeight
            // if(multiple > 1 && nodes[index].offsetTop )
            // if (pageHeight > 0 && nodes[index].offsetTop + nodes[index].offsetHeight > pageHeight) {
            //     return true
            // }
            if(isTopHeight && isPageHeight){
                return true
            }
            return false
        },

        hidenView() {
            this.showView = false;
            this.$emit('hiden-view')
        },

    }
}
</script>

<style>
    .close {
        display: block;
        width: 40px;
        height: 40px;
        margin-right: -10px;
        padding: 10px;
        cursor: pointer;
    }
</style>